<?php

namespace app\api\controller;

use Exception;
use think\Cache;
use think\Controller;
use think\Log;
use think\Request;


class Long extends Controller
{
    private $appSecret = 'a38f72e2daf57349516e575677839c89';
    private $appid = 'wx7a82ee3ed7482fb5';

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
        // parent::__construct();
        // set_cors();
    }
    //根据渠道获取公告
    public function channel_inform()
    {
        $params = Request::instance()->param();

        $res = db('channel', 'db_operatelog_tabi_data')->where(['channel_id' => $params['channel_id']])->find();
        if($res['is_gonggao'] == 1){
            $res = db('config', 'db_operatelog_tabi_data')->where(['type' => 'gonggao'])->find();
            exit(json_encode(['is_true'=>1,'content'=>$res['content']]));
        }
        exit(json_encode(['is_true'=>0,'content'=>'']));
    }
    public function config()
    {
        $params = Request::instance()->param();

        $Res = db('config', 'db_operatelog_tabi_data')->where(['type' => $params['type']])->find();
        exit(json_encode($Res));
    }
    public function user()
    {
        $params = Request::instance()->param();
        $accounts = db('accounts', 'db_operatelog_tabi_server')->where([
            'UserId' => $params['userid']
        ])
            ->where('RegisterTime', '<=', date('Y-m-d'))
            ->where('RegisterTime', '>=', date('Y-m-d', strtotime('-1 day')))
            ->find();
        if ($accounts) {
            exit('true');
        } else {
            exit('false');
        }
    }

    //高塔对决
    public function code()
    {
        try {
            $params = Request::instance()->param();
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxd00d17695afd9ec6&secret=a3e1a6e42ecd116484082a96813df1b7&js_code=' . $params['code'] . '&grant_type=authorization_code';
            $res = file_get_contents($url);
            exit($res);
        } catch (\Exception $e) {
        }
    }
    //龙宫传奇
    public function w_code()
    {
        try {
            $params = Request::instance()->param();
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx7a82ee3ed7482fb5&secret=a38f72e2daf57349516e575677839c89&js_code=' . $params['code'] . '&grant_type=authorization_code';
            $res = file_get_contents($url);
            exit($res);
        } catch (\Exception $e) {
        }
    }
    public function ad_point()
    {
        try {
            $params = Request::instance()->param();
            if (empty($params['channel']) || empty($params['code']) || empty($params['user_id'])) {
                exit('缺少参数');
            }

            //是否是首次触发广告
            $ad_point = db('ad_point', 'db_operatelog_tabi_data')->where(['user_id' => $params['user_id'], 'is_one'=>1])->find();
            if ($ad_point) {
                db('ad_point', 'db_operatelog_tabi_data')->insert([
                    'date' => date('Y-m-d H:i:s'),
                    'channel' => $params['channel'],
                    'type' => $params['code'],
                    'user_id' => $params['user_id'],
                ]);
            } else {
                db('ad_point', 'db_operatelog_tabi_data')->insert([
                    'date' => date('Y-m-d H:i:s'),
                    'channel' => $params['channel'],
                    'type' => $params['code'],
                    'user_id' => $params['user_id'],
                    'is_one'=>1
                ]);
            }
            exit('true');
        } catch (\Exception $e) {
            var_dump($e->getMessage() . $e->getLine());
            die;
        }
    }
    public function point()
    {
        try {
            $params = Request::instance()->param();
            $channel = $params['channel'];
            $Res = db('point', 'db_operatelog_tabi_data')->where([
                'date' => date('Y-m-d'),
                'channel' => $channel,
                'type' => $params['code']
            ])->find();
            if ($Res) {
                db('point', 'db_operatelog_tabi_data')->where([
                    'date' => date('Y-m-d'),
                    'channel' => $channel,
                    'type' => $params['code']
                ])->update([
                    'count' => $Res['count'] + 1
                ]);
            } else {
                db('point', 'db_operatelog_tabi_data')->insert([
                    'date' => date('Y-m-d'),
                    'type' => $params['code'],
                    'channel' => $channel,
                    'count' => 1
                ]);
            }
            exit('true');
        } catch (\Exception $e) {
            var_dump($e->getMessage() . $e->getLine());
            die;
        }
    }
    public function feedback()
    {
        try {
            $params = Request::instance()->param();

            db('feedback', 'db_operatelog_tabi_data')->insert([
                'date' => date('Y-m-d H:i:s'),
                'userid' => $params['userid'],
                'content' => $params['content'],
            ]);
            exit('true');
        } catch (\Exception $e) {
            var_dump($e->getMessage() . $e->getLine());
            die;
        }
    }

    public function ad()
    {
        $params = Request::instance()->param();
        $res = db('ad_douyin', 'db_operatelog_tabi_data')->where(['clickid' => $params['clickid']])->find();
        if ($res) {
            $obj = [
                'code' => 0,
                'message' => '成功'
            ];
            exit(json_encode($obj));
        }
        db('ad_douyin', 'db_operatelog_tabi_data')->insert([
            'adid' => $params['adid'],
            'clickid' => $params['clickid'],
            'creativeid' => $params['creativeid'],
            'creativetype' => $params['creativetype'],
            'date' => date('Y-m-d H:i:s'),
        ]);

        mylog($params);
        $obj = [
            'code' => 0,
            'message' => '成功'
        ];
        exit(json_encode($obj));
    }
    public function callback()
    {
        $params = Request::instance()->param();
        mylog($params);
        $event_type = $params['event_type'];
        $ad_douyin = db('ad_douyin', 'db_operatelog_tabi_data')->where(['clickid' => $params['clickid']])->find();
        if (!$ad_douyin) {
            exit(json_encode(['code' => 1, 'message' => '未找到clickid']));
        }

        //是否是次留
        if ($event_type == 'login') {
                $accounts = db('accounts', 'db_operatelog_tabi_server')->where([
                    'UserId' => $params['userid']
                ])
                ->where('RegisterTime', '<=', date('Y-m-d'))
                ->where('RegisterTime', '>=', date('Y-m-d', strtotime('-1 day')))
                ->find();
            if ($accounts) {
                $event_type = 'next_day_open';
            } else {
                exit(json_encode(['code' => 1, 'message' => '不是次留']));
            }
        }

        //拦截一个用户多次上次同一个事件
        $userid = db('ad_douyin', 'db_operatelog_tabi_data')->where([
            'user_id' => $params['userid'],
            $event_type => 1,
        ])->find();
        if ($userid) {
            mylog('拦截一个用户多次上次同一个事件');
            exit(json_encode(['code' => 1, 'message' => '用户已经触发过']));
        }

        $data = array(
            "event_type" => $event_type,
            "context" => [
                'ad' => ['callback' => $params['clickid']]
            ],
            'timestamp' => round(microtime(true) * 1000)
        );
        $url = 'https://analytics.oceanengine.com/api/v2/conversion';
        $jsonData = json_encode($data);
        $res = $this->callback_url($jsonData, $url);
        $data = json_decode($res, true);
        if ($data['code'] == 0) {
            db('ad_douyin', 'db_operatelog_tabi_data')->where(['clickid' => $params['clickid']])->update([
                $event_type => 1,
                'user_id' => $params['userid'],
            ]);
            exit(json_encode(['code' => 0, 'message' => '成功']));
        }
        return $res;
    }
    public function callback_url($jsonData, $url)
    {
        // 初始化一个 CURL 会话
        $ch = curl_init();
        // 设置请求的 URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // 设置请求方法为 POST
        curl_setopt($ch, CURLOPT_POST, true);
        // 设置 POST 数据，这里是 JSON 字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        // 设置请求头，指定 Content-Type 为 application/json
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        ));
        // 要求 CURL 函数在执行后返回请求的结果，而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        // 执行 CURL 请求
        $response = curl_exec($ch);
        // 关闭 CURL 会话
        curl_close($ch);
        mylog($response);
        return $response;
    }

    public function scheme()
    {
        $params = Request::instance()->param();
        mylog($params);
        $sign = $this->sign($params['nonce'], $params['timestamp']);
        if ($sign != $params['signature']) {
            $obj = [
                'code' => 40004,
                'url_scheme' => ''
            ];
            exit(json_encode($obj));
        }
        $res = $this->token();
        $data = json_decode($res, true);
        $token = $data['access_token'];
        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token;
        $res  = json_decode($this->request_by_curl($url), true);
        $obj = [
            'code' => 0,
            'url_scheme' => $res['openlink']
        ];
        exit(json_encode($obj));
    }
    public function token()
    {
        $token = Cache::get('wx-token1');
        if (!empty($token)) {
            return $token;
        }
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd00d17695afd9ec6&secret=a3e1a6e42ecd116484082a96813df1b7');
        Cache::set('wx-token1', $res, 5000);
        return $res;
    }

    function request_by_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '');

        // 执行 cURL 请求
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public function sign($nonce, $timestamp)
    {
        $token = '3D3DFD64226A7489C6664C5DB214F29F';
        $collect = array((string)$token, (string)$nonce, (string)$timestamp);
        usort($collect, 'strcmp');
        $signature = sha1(implode('', $collect));
        return $signature;
    }

    public function juliang_ios()
    {
        $params = Request::instance()->param();
        mylog($params);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }

    public function juliang_android()
    {
        $params = Request::instance()->param();
        mylog($params);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }

    public function juliang_callback()
    {
        $params = Request::instance()->param();
        mylog($params);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }
    public function juliang_url()
    {
        // get cURL resource

        $ch = curl_init();
        $callback = 'B.GzSxpi9B7C55FIeZx9Nk23Lkc6sUgoys4eqNttceafhpFx5mkDDeQZDZedjNnRaKgelRThQvRwVGyo1XfanVPrTn0puItqE3Nmu7F4WfrgirMyhEcdEMjERzOgYdfxr6le9kunLfGcPZnwpEsAp8wiEC';
        $url = "https://ad.oceanengine.com/track/activate/?callback=$callback&amp;event_type=0";

        // set url
        curl_setopt($ch, CURLOPT_URL, $url);

        // set method
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

        // return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        // send the request and save response to $response
        $response = curl_exec($ch);

        // stop if fails
        if (!$response) {
            die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
        }

        echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
        echo 'Response Body: ' . $response . PHP_EOL;

        // close curl resource to free up system resources
        curl_close($ch);
    }

    public function tengxun()
    {
        $params = Request::instance()->param();
        mylog($params);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }

    public function tengxun_callback()
    {
        $params = Request::instance()->param();
        mylog($params);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }

    //支付订单
    public function order(){
        $params = Request::instance()->param();


        $res = db('order', 'db_operatelog_tabi_data')->insert([
            'user_id'=>$params['user_id'],
            'amount'=>$params['amount'],
            'date'=>date('Y-m-d H:i:s'),
        ]);
        exit(json_encode(['code' => 0, 'msg' => '成功']));
    }
    //查询最近一个月的充值金额
    public function get_amount(){
        $params = Request::instance()->param();
        $currentTime = time();
        // 获取月初日期
        $startOfMonth = strtotime('first day of this month', $currentTime);
        $startOfMonthStr = date('Y-m-d 00:00:00', $startOfMonth);
        // 获取月末日期
        $endOfMonth = strtotime('last day of this month', $currentTime);
        $endOfMonthStr = date('Y-m-d 23:59:59', $endOfMonth);

        $amount = db('order', 'db_operatelog_tabi_data')
        ->where(['user_id'=>$params['user_id']])
        ->where('date','>=',$startOfMonthStr)
        ->where('date','<=',$endOfMonthStr)
        ->sum('amount');
        exit(json_encode(['code' => 0, 'amount' => $amount]));
    }
}
